import https from 'https'
import fs from 'fs'
import md5 from 'md5'

export default class Translate {
    root = './language/' // 根目录
    startLang = "zh" // 翻译前的 语言
    endLang = "kor" // 翻译后的 语言
    appid = '' // 百度翻译 appid
    key = '' // 百度翻译 密钥
    reg = /(:|: )('|"|`|\[|\{)(.*)[('|"|`|\]|\})$]/g;
    start = false
    callback = ()=>{}

    dataObj = {}

    constructor(options){
        this.appid = options.appid||this.appid;
        this.key = options.key||this.key;
    }

    setOpt(options) {
        this.key = options.key||this.key;
        this.appid = options.appid||this.appid;
        this.endLang = options.endLang||this.endLang;
        this.startLang = options.startLang||this.startLang;
    }

    // 随机数
    randomRangeNumber(minNumber, maxNumber) {
        var range = maxNumber - minNumber;
        var random = Math.random();
        return minNumber + Math.round(random * range);
    }

    // 百度翻译
    http(q){
        let salt = this.randomRangeNumber(1000000000,9999999999)
        q = q instanceof Array?q.join('\n'):q;
                    
        console.log(q);
        return new Promise((resolve, reject) => {
            if(!q) return resolve({})
            let path = `/api/trans/vip/translate?q=${q}&from=${this.startLang}&to=${this.endLang}&appid=${this.appid}&salt=${salt}&sign=${md5(this.appid+q+salt+this.key)}`
            var req = https.request({
                host: 'fanyi-api.baidu.com',
                path: encodeURI(path),
                method: 'POST',
                agent: false
            }, (res) => {
                let data = ''
                res.on('data', (d) => {
                    data+=d
                });
                res.on('end', (d) => {
                    data = JSON.parse(data)
                    console.log(data);
                    if(data.error_code) {
                        this.start = false
                        console.log('翻译报错');
                        this.callback({message: data.error_msg,error_code: data.error_code, code: 500})
                        reject(data)
                    } else {
                        resolve(data.trans_result.reduce((obj,item)=>({...obj,[item.src]:(item.dst+'').replace(/\s*/g,"").replace("...","").replace(",',",",'',")}),{}))
                    }
                });
            })
            req.on('error', (e) => {
                reject(e)
                console.error(e);
            });
            req.end();
        })
    }

    // 分割数组
    spArr(arr, num) {
        let newArr = []
        for (let i = 0; i < arr.length;) {
            newArr.push(arr.slice(i, i += num));
        }
        return newArr
    }

    // 读取文件
    startFN(callback){
        console.log('files',this.endLang);
        this.callback = callback;
        fs.readdir(this.root+this.startLang,(err,files)=>{
            if(!err) {
                console.log(files);
                files.forEach(path => {
                    if(true){
                        fs.readFile(this.root+this.startLang+'/'+path, "utf8", async (err, data) => {
                            if(!err) {
                                let text = data.toString()
                                let arr = []
                                text.replace(this.reg,(a,b,c,d,e)=>{
                                    if(c == '[') d = '-'+d
                                    arr.push(d.replace(/"/g,"'").replace(/\s*/g,""))
                                })
                                arr = this.spArr(arr,300)||[]
                                console.log(path.replace(this.startLang,this.endLang.toLocaleLowerCase()));
                                this.dataObj[path.replace(this.startLang,this.endLang.toLocaleLowerCase())] = {arr,text}
                                !this.start && this.translate()
                            }
                        })
                    }
                })
            } else {
                console.log(err);
            }
        })
    }

    // 更新翻译数据
    async translate(objs,ii,k){
        this.start = true;
        let obj = {}, l = ii||0, arr = [], key = k||''
        if (!objs){
            let keys = Object.keys(this.dataObj);
            if(!keys[0]) {
                this.start = false
                this.callback();
                console.log('翻译结束')
                return
            }
            console.log('start: ' + keys[0]);
            arr = this.dataObj[keys[0]].arr;
            l = arr.length-1;
            key = keys[0];
            obj = await this.http(arr[0])
        } else {
            arr = this.dataObj[key].arr;
            let obj1 = await this.http(arr[arr.length-l-1])
            obj = {...objs,...obj1}
        }

        console.log(key,'this.dataObj');
        if(l) {
            setTimeout(()=>{
                this.translate(obj,l-1,key) 
            },2000)
            return
        }
        // console.log(obj);
        // return
        let dd = this.dataObj[key].text.replace(this.reg,function(a,b,c,d){
            let c1 = d.replace(/"/g,"'").replace(/\s*/g,"")
            if(c == '{') {
                let v = obj[c1]?obj[c1].charAt(obj[c1].length-1)=="'"?obj[c1]:obj[c1]+"'":'**';
                return `:{${v}}`
            }else if(c == '[') {
                let v = obj['-'+c1].replace(/^-/,'').replace(/\.$/,'')
                return `:[${v}]`
            } else {
                return '"name":`'+obj[c1]+'`'
            }
        })
        
        dd = dd.replace(RegExp(this.startLang,'g'),this.endLang.toLocaleLowerCase())
        !fs.existsSync(`${this.root}${this.endLang}`) && fs.mkdirSync(`${this.root}${this.endLang}`)
        fs.writeFileSync(`${this.root}${this.endLang}/${key}`,dd);

        console.log('success: ' + key);
        delete this.dataObj[key];
        setTimeout(()=>{
            this.translate() 
        },2000)
    }
}

// new Translate()